package com.zy.service.impl;


import com.zy.dto.Result;
import com.zy.entity.ShopType;
import com.zy.mapper.ShopTypeMapper;
import com.zy.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;
import java.util.Set;

import static com.zy.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张宇
 * @since 2024-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询商铺类型列表
     *
     * @return
     */
    @Override
    public Result queryTypeList() {
        // 1.从redis查询商铺类型缓存
        Set<ShopType> shopTypeSet = redisTemplate.opsForZSet().range(CACHE_SHOP_TYPE_KEY, 0, -1);
        // 2.判断是否存在
        if (shopTypeSet != null && shopTypeSet.size() > 0){
            // 3.存在,将set转为list并返回
            return Result.ok(new ArrayList<ShopType>(shopTypeSet));
        }
        // 4.不存在,查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        if (shopTypeList == null){
            // 5.不存在,返回404
            return Result.fail("店铺类型不存在");
        }
        // 6.存在写入redis
        shopTypeList.forEach(shopType -> redisTemplate.opsForZSet().add(CACHE_SHOP_TYPE_KEY, shopType, shopType.getSort()));
        // 6.返回
        return Result.ok(shopTypeList);
    }
}
